/**
 * 
 */
package cn.com.jsepc.rep.comm;

import java.math.BigDecimal;

/**
 * @author liangyx
 *
 */
public class NumberFormatUtils {

	private static final int DEF_DIV_SCALE = 2;
	/**
	 * 提供精确的加法 a + b
	 * @param a
	 * @param b
	 * @return
	 */
	public static String add(String a, String b){
		a = StringUtils.nil(a, "0");
		b = StringUtils.nil(b, "0");
		BigDecimal a1 = new BigDecimal(a);
		BigDecimal b1 = new BigDecimal(b);
		BigDecimal sum = a1.add(b1);
		return sum.toString();
	}
	
	/**
	 * 提供精确的减法 a - b
	 * @param a
	 * @param b
	 * @return
	 */
	public static String sub(String a, String b){
		BigDecimal a1 = new BigDecimal(a);
		BigDecimal b1 = new BigDecimal(b);
		return a1.subtract(b1).toString();
	}
	/**
	 * 提供精确的除法 a/b
	 * @param a
	 * @param b
	 * @return
	 */
	public static String divide(String a, String b){
		a = StringUtils.nil(a, "0");
		b = StringUtils.nil(b, "0");
		if(b.equals("0")){
			return "0";
		}
		BigDecimal a1 = new BigDecimal(a);
		BigDecimal b1 = new BigDecimal(b);
		BigDecimal r = a1.divide(b1, DEF_DIV_SCALE, BigDecimal.ROUND_HALF_UP);
		return r.toString();
	}
	
	/**
	 * 提供精确的乘法 a * b
	 * @param a
	 * @param b
	 * @return
	 */
	public static String mul(String a, String b){
		a = StringUtils.nil(a, "0");
		b = StringUtils.nil(b, "0");
		BigDecimal a1 = new BigDecimal(a);
		BigDecimal b1 = new BigDecimal(b);
		return a1.multiply(b1).toString();
	}
	
	private static final BigDecimal ONE = new BigDecimal("1");
	/**
	 * 提供精确的四舍五入处理
	 * @param v 
	 * @param scale 小数保留位数
	 * @return
	 */
	public static String round(String v, int scale){
		BigDecimal v1 = new BigDecimal(v);
		return v1.divide(ONE, scale, BigDecimal.ROUND_HALF_UP).toString();
	}
	
	/**
	 * 比较2个值 x>=y 返回true
	 * @param x
	 * @param y
	 * @return boolean
	 */
	public static boolean compare(String x, String y){
		BigDecimal x1 = new BigDecimal(x);
		int t = x1.compareTo(new BigDecimal(y));
		return t >= 0;
	}
	/**
	 * 比较2个值 x==y 返回true
	 * @param x
	 * @param y
	 * @return boolean
	 */
	public static boolean compareE(String x, String y){
		BigDecimal x1 = new BigDecimal(x);
		int t = x1.compareTo(new BigDecimal(y));
		return t == 0;
	}
	
	public static final void main(String[] args){
		System.out.println(NumberFormatUtils.compare("23.20", "12.10"));
		System.out.println(NumberFormatUtils.compare("23.20", "23.40"));
		System.out.println(NumberFormatUtils.add("23.212", "12.123"));
		System.out.println(NumberFormatUtils.divide("23.20", "12.10"));
		System.out.println(NumberFormatUtils.sub("23.212", "12.123"));
		System.out.println(NumberFormatUtils.mul("23.20", "12.10"));
		System.out.println(NumberFormatUtils.round(NumberFormatUtils.sub("23.212", "12.123"), 2));
	}
}
